﻿using System;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Routing;

namespace rossisdead.Mvc.Detergent
{
    internal static class RouteCollectionExtensions
    {
        /// <summary>
        /// Returns RouteData for an arbitrary Uri.
        /// </summary>
        public static RouteData GetRouteData(this RouteCollection routeCollection, Uri uri)
        {
            using (var sw = new StringWriter())
            {
                var httpContext = new HttpContext(GetRequest(uri), new HttpResponse(sw));
                return routeCollection.GetRouteData(new HttpContextWrapper(httpContext));
            }
        }

        private static HttpRequest GetRequest(Uri uri)
        {
            var absolute = uri.AbsoluteUri;
            if (absolute.Contains("?"))
            {
                absolute = absolute.Split('?').First();
            }
            return new HttpRequest(null, absolute, uri.Query);
        }
    }
}
